# coding=utf-8
import json
from datetime import datetime

from flask import jsonify

from blues.cloud import bp
from blues.cloud.base import request_asapi
from database2 import db_exec_many
from model.c_department import find_all_depart
from public.time_utils import get_last_2days_0hour


def record_cms_oss() -> bool:
    yesterday_0hour, today_0hour = get_last_2days_0hour()
    yesterday = yesterday_0hour.rstrip(" 00:00:00")
    now = datetime.now()
    # 初始化一个空字典，稍后遍历depart并调用asapi后，将监控数据填充到res中
    values_list = []

    # 对于专有云，只能通过部门ak sk获取cms信息
    depart_list = find_all_depart()
    for depart in depart_list:
        cloud_id = depart['cloud_id']
        depart_ak = depart['access_key_id']
        depart_sk = depart['access_key_secret']
        depart_id = depart['department']
        depart_name = depart['department_name']
        print(cloud_id, depart_id, depart_name)

        # 获取ASAPI接口数据
        params = {
            "Namespace": "acs_oss_dashboard",
            "Period": "86400",
            "StartTime": yesterday_0hour,
            "EndTime": today_0hour,
            'MetricName': "MeteringStorageUtilization"
        }
        asapi_data = request_asapi(cloud_id, "Cms", "2019-01-01", "DescribeMetricLast", params, ak=depart_ak,
                                   sk=depart_sk)
        # print(asapi_data)
        if not asapi_data:
            return False
        data_points = json.loads(asapi_data['Datapoints'])
        # 由于使用了DescribeMetricLast，每个bucket只会返回一个values值
        for i in data_points:
            # 跳过 "quota_for_get_service_" 这个内置的用于计费的bucket
            if i['BucketName'] == 'quota_for_get_service_':
                continue
            tmp_tuple = (i['BucketName'], i['Value'], cloud_id, depart_id, depart_name, yesterday, now)
            values_list.append(tmp_tuple)

    table = 'cms_oss'
    fields = "bucket,value,cloud_id,depart_id,depart_name,`date`,record_time"
    # 使用上面的数据，批量插入db
    db_success = db_exec_many(table, fields, values_list)
    if not db_success:
        return False
    return True


@bp.route('/api/v1/cloud/record_cms_oss', methods=['POST'])
def record_cms_oss_api():
    success = record_cms_oss()
    if not success:
        return jsonify({'code': 500})
    return jsonify({'code': 200})
